import { PlusOutlined, EditOutlined, DeleteOutlined, EyeOutlined, CheckOutlined, CloseOutlined } from '@/utils/icons';
import React, { useState, useEffect } from 'react';
import { Card, Table, Button, Space, Modal, Form, Input, InputNumber, Select, DatePicker, message, Upload, Tag, Descriptions } from 'antd';

import { expenseApi } from '../../api/expenseApi';
import dayjs from 'dayjs';

const { Option } = Select;
const { TextArea } = Input;

export default function ExpenseManagement() {
  const [loading, setLoading] = useState(false);
  const [expenseList, setExpenseList] = useState([]);
  const [modalVisible, setModalVisible] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [editingRecord, setEditingRecord] = useState(null);
  const [selectedRecord, setSelectedRecord] = useState(null);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchExpenseList();
  }, []);

  const fetchExpenseList = async () => {
    setLoading(true);
    try {
      const response = await expenseApi.getExpenseList();
      setExpenseList(response.data);
    } catch (error) {
      message.error('获取报销列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleAdd = () => {
    setEditingRecord(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (record) => {
    setEditingRecord(record);
    form.setFieldsValue({
      ...record,
      expenseDate: record.expenseDate ? dayjs(record.expenseDate) : null,
    });
    setModalVisible(true);
  };

  const handleView = (record) => {
    setSelectedRecord(record);
    setDetailVisible(true);
  };

  const handleDelete = async (id) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这条报销申请吗？',
      onOk: async () => {
        try {
          await expenseApi.deleteExpense(id);
          message.success('删除成功');
          fetchExpenseList();
        } catch (error) {
          message.error('删除失败');
        }
      },
    });
  };

  const handleSubmit = async (values) => {
    try {
      const data = {
        ...values,
        expenseDate: values.expenseDate ? values.expenseDate.format('YYYY-MM-DD') : null,
      };

      if (editingRecord) {
        await expenseApi.updateExpense(editingRecord.id, data);
        message.success('更新成功');
      } else {
        await expenseApi.createExpense(data);
        message.success('创建成功');
      }
      
      setModalVisible(false);
      fetchExpenseList();
    } catch (error) {
      message.error(editingRecord ? '更新失败' : '创建失败');
    }
  };

  const handleSubmitExpense = async (id) => {
    try {
      await expenseApi.submitExpense(id);
      message.success('提交成功');
      fetchExpenseList();
    } catch (error) {
      message.error('提交失败');
    }
  };

  const handleApprove = async (id) => {
    Modal.confirm({
      title: '审批通过',
      content: '确定要审批通过这条报销申请吗？',
      onOk: async () => {
        try {
          await expenseApi.approveExpense(id, { remark: '审批通过' });
          message.success('审批成功');
          fetchExpenseList();
        } catch (error) {
          message.error('审批失败');
        }
      },
    });
  };

  const handleReject = async (id) => {
    Modal.confirm({
      title: '审批拒绝',
      content: '确定要拒绝这条报销申请吗？',
      onOk: async () => {
        try {
          await expenseApi.rejectExpense(id, { remark: '审批拒绝' });
          message.success('拒绝成功');
          fetchExpenseList();
        } catch (error) {
          message.error('操作失败');
        }
      },
    });
  };

  const columns = [
    {
      title: '申请单号',
      dataIndex: 'expenseNo',
      key: 'expenseNo',
    },
    {
      title: '申请人',
      dataIndex: 'applicant',
      key: 'applicant',
    },
    {
      title: '报销类型',
      dataIndex: 'expenseType',
      key: 'expenseType',
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      render: (value) => `¥${value.toLocaleString()}`,
    },
    {
      title: '申请日期',
      dataIndex: 'expenseDate',
      key: 'expenseDate',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => {
        const statusMap = {
          draft: { color: 'default', text: '草稿' },
          pending: { color: 'orange', text: '待审批' },
          approved: { color: 'green', text: '已通过' },
          rejected: { color: 'red', text: '已拒绝' },
          paid: { color: 'blue', text: '已支付' },
        };
        const config = statusMap[status] || { color: 'default', text: status };
        return <Tag color={config.color}>{config.text}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button type="link" icon={<EyeOutlined />} size="small" onClick={() => handleView(record)}>
            查看
          </Button>
          {record.status === 'draft' && (
            <>
              <Button type="link" icon={<EditOutlined />} size="small" onClick={() => handleEdit(record)}>
                编辑
              </Button>
              <Button type="link" icon={<CheckOutlined />} size="small" onClick={() => handleSubmitExpense(record.id)}>
                提交
              </Button>
            </>
          )}
          {record.status === 'pending' && (
            <>
              <Button type="link" icon={<CheckOutlined />} size="small" onClick={() => handleApprove(record.id)}>
                通过
              </Button>
              <Button type="link" icon={<CloseOutlined />} size="small" danger onClick={() => handleReject(record.id)}>
                拒绝
              </Button>
            </>
          )}
          <Button type="link" icon={<DeleteOutlined />} size="small" danger onClick={() => handleDelete(record.id)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
              新增报销
            </Button>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={expenseList}
          loading={loading}
          rowKey="id"
          pagination={{
            total: expenseList.length,
            pageSize: 10,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
        />
      </Card>

      <Modal
        title={editingRecord ? '编辑报销' : '新增报销'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="expenseType"
            label="报销类型"
            rules={[{ required: true, message: '请选择报销类型' }]}
          >
            <Select>
              <Option value="差旅费">差旅费</Option>
              <Option value="交通费">交通费</Option>
              <Option value="餐费">餐费</Option>
              <Option value="办公用品">办公用品</Option>
              <Option value="通讯费">通讯费</Option>
              <Option value="其他">其他</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="amount"
            label="报销金额"
            rules={[{ required: true, message: '请输入报销金额' }]}
          >
            <InputNumber
              style={{ width: '100%' }}
              formatter={value => `¥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
              parser={value => value.replace(/¥\s?|(,*)/g, '')}
            />
          </Form.Item>

          <Form.Item
            name="expenseDate"
            label="报销日期"
            rules={[{ required: true, message: '请选择报销日期' }]}
          >
            <DatePicker style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item
            name="description"
            label="报销说明"
            rules={[{ required: true, message: '请输入报销说明' }]}
          >
            <TextArea rows={4} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title="报销详情"
        open={detailVisible}
        onCancel={() => setDetailVisible(false)}
        footer={null}
        width={800}
      >
        {selectedRecord && (
          <Descriptions bordered column={2}>
            <Descriptions.Item label="申请单号">{selectedRecord.expenseNo}</Descriptions.Item>
            <Descriptions.Item label="申请人">{selectedRecord.applicant}</Descriptions.Item>
            <Descriptions.Item label="报销类型">{selectedRecord.expenseType}</Descriptions.Item>
            <Descriptions.Item label="报销金额">¥{selectedRecord.amount.toLocaleString()}</Descriptions.Item>
            <Descriptions.Item label="报销日期">{selectedRecord.expenseDate}</Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={selectedRecord.status === 'approved' ? 'green' : 'orange'}>
                {selectedRecord.status === 'approved' ? '已通过' : '待审批'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="报销说明" span={2}>
              {selectedRecord.description}
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </div>
  );
}
